package com.spagettikod.t437.simpledb;

import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableColumn;

import com.spagettikod.t437.T437;
import com.xerox.amazonws.sdb.Domain;

public class SimpleDBJTable extends JTable
{
	private static final long serialVersionUID = 2741534052269090471L;

	public SimpleDBJTable()
	{
		super();
		setAutoResizeMode(AUTO_RESIZE_OFF);
		setAutoCreateRowSorter(true);
	}

	public void setDomain(Domain domain)
	{
		setModel(new SimpleDBTableModel(domain));
	}

	private int getVisibleRows()
	{
		Float rows = new Float(T437.getApplicationFrame().getSize().height) / new Float(getRowHeight());
		return Math.round(rows.floatValue());
	}

	public void queryData(String queryString)
	{
		if (getModel() instanceof SimpleDBTableModel)
		{
			((SimpleDBTableModel) getModel()).queryData(queryString, getVisibleRows());
		}
	}

	public void fetchData(String queryString, boolean forceFetch)
	{
		if (getModel() instanceof SimpleDBTableModel)
		{
			((SimpleDBTableModel) getModel()).fetchData(queryString, getVisibleRows(), forceFetch);
		}
	}

	public void fitColumnWidthsToContent()
	{
		for (int col = 0; col < getModel().getColumnCount(); col++)
		{
			TableColumn tblColumn = getColumnModel().getColumn(col);
			int width = tblColumn.getPreferredWidth();
			for (int row = 0; row < getModel().getRowCount(); row++)
			{
				JLabel l = (JLabel) getCellRenderer(row, col).getTableCellRendererComponent(this, getValueAt(row, col),
						false, false, row, col);
				int newWidth = getIntercellSpacing().width + l.getPreferredSize().width;
				width = Math.max(width, newWidth);
			}
			tblColumn.setPreferredWidth(width);
		}
	}
}
